package com.zhkc.wisdom.common.web.handler;

import com.zhkc.wisdom.common.base.exception.BusinessException;
import com.zhkc.wisdom.common.pojo.enums.ResponseCodeEnum;
import com.zhkc.wisdom.common.pojo.vo.ResultVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * Description:自定义全局异常处理器
 * User: zzw
 * Date: 2023/8/17
 * Time: 13:38
 * company:zhkc
 */
@SuppressWarnings("ALL")
@RestControllerAdvice
@Slf4j
public class DefineGlobalExceptionHandler {
    /**
     * @Description 参数绑定异常
     * @Author zzw
     * @Date 13:39 2023/8/17
     **/
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultVO<String> bindException(HttpServletRequest request,
                                          HttpServletResponse response,
                                          BindException exception) {
        log.error(exception.getMessage(), exception);
        return ResultVO.fail(exception.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * @Description BusinessException
     * @Author zzw
     * @Date 13:40 2023/8/17
     **/
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultVO<String> exception(HttpServletRequest request,
                                      HttpServletResponse response,
                                      BusinessException exception) {
        log.error(exception.getErrorMsg(), exception);
        return ResultVO.fail(exception.getErrorMsg());
    }

    /**
     * @Description 其他异常
     * @Author zzw
     * @Date 13:40 2023/8/17
     **/
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ResultVO<String> exception(HttpServletRequest request,
                                      HttpServletResponse response,
                                      Exception exception) {
        log.error(exception.getMessage(), exception);
        return ResultVO.fail(ResponseCodeEnum.FAIL);
    }


}

